<template>
  <div class="app-container">
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="45%"
      v-dialogDrag
      append-to-body
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        v-loading="formLoading"
        label-width="100px"
      >
        <el-form-item label="导航栏信息名称" prop="title">
          <el-input
            v-model="formData.title"
            placeholder="请输入导航栏信息名称"
          />
        </el-form-item>
        <el-form-item label="导航栏信息地址" prop="imageUrl">
          <el-input
            v-model="formData.imageUrl"
            placeholder="请输入导航栏信息地址"
            @input="onImageUrlChange"
          />
          <div v-if="formData.imageUrl" class="image-preview">
            <img :src="formData.imageUrl" alt="图片预览" class="preview-image" />
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="formLoading">
          确 定
        </el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as NavApi from "@/api/system/nav";

export default {
  name: "NavForm",
  data() {
    return {
      dialogTitle: "",
      dialogVisible: false,
      formLoading: false,
      formData: {
        id: undefined,
        title: undefined,
        imageUrl: undefined,
      },
      formRules: {
        title: [
          { required: true, message: "名称不能为空", trigger: "blur" },
          {
            max: 50,
            message: "名称长度不能超过50个字符",
            trigger: "blur",
          },
        ],
        imageUrl: [
          { required: true, message: "地址不能为空", trigger: "blur" },
          {
            type: "url",
            message: "请输入有效的URL地址",
            trigger: ["blur", "change"],
          },
          {
            pattern: /\.(jpg|png|gif|webp)$/i,
            message: "仅支持图片格式（jpg/png/gif/webp）",
            trigger: ["blur", "change"],
          },
        ],
      },
    };
  },
  methods: {
    async open(id) {
      this.dialogVisible = true;
      this.reset();
      if (id) {
        try {
          this.formLoading = true;
          const { data } = await NavApi.getNav(id);
          this.formData = data;
          this.dialogTitle = "修改导航栏信息";
        } finally {
          this.formLoading = false;
        }
      } else {
        this.dialogTitle = "新增导航栏信息";
      }
    },

    async submitForm() {
      try {
        await this.$refs.formRef.validate();
        const postData = {
          id: this.formData.id,
          title: this.formData.title,
          imageUrl: this.formData.imageUrl,
        };
        this.formLoading = true;
        if (this.formData.id) {
          await NavApi.updateNav(postData);
          this.$modal.msgSuccess("修改成功");
        } else {
          await NavApi.createNav(postData);
          this.$modal.msgSuccess("新增成功");
        }
        this.dialogVisible = false;
        this.$emit("success");
      } catch (error) {
        if (error instanceof Error) {
          this.$modal.msgError(
            error.response?.data?.msg || error.message || "操作失败，请检查网络连接"
          );
        }
      } finally {
        this.formLoading = false;
      }
    },

    reset() {
      this.formData = {
        id: undefined,
        title: undefined,
        imageUrl: undefined,
      };
      this.$nextTick(() => {
        this.$refs.formRef?.clearValidate();
      });
    },

    onImageUrlChange() {
      if (this.formData.imageUrl) {
        const isValidUrl = /^(https?:\/\/).+\.(jpg|png|gif|webp)$/i.test(this.formData.imageUrl);
        if (!isValidUrl) {
          this.$message.error("请输入有效的图片URL（支持jpg/png/gif/webp）");
          this.formData.imageUrl = ""; // 清空无效的图片地址
        }
      }
    }
  },
};
</script>

<style scoped>
.image-preview {
  margin-top: 10px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.preview-image {
  max-width: 100%;
  max-height: 200px;
  border: 1px solid #ccc;
  border-radius: 4px;
}
</style>